package Window;

import Tools.Tool;
import entity.Basket;
import entity.Dessert;
import entity.score.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Game extends JFrame {
    Random ran=new Random();
        Tool tool=new Tool();
       //Image image=;
      List<Dessert> list=new ArrayList<>();

      int num=0;//判断频率
    ImageIcon imgBg=new ImageIcon("src/res/03.jpg");

    BackGrund backGrund=new BackGrund();//实例化背景类
    Basket basket=new Basket();//实例化购物篮
    Score scoreBg=new Score();//实例化分数板
    S1 s1=new S1();//实例化分数板
    S2 s2=new S2();//实例化分数板
    S3 s3=new S3();//实例化分数板
    S4 s4=new S4();//实例化分数板

    //实例化蛋糕类
    //Dessert dessert=new Dessert();
    Image offScreenImage;
    public Game(){
        init();
    }
    public void init(){

       this.setSize(basket.imageBg.getWidth(null),basket.imageBg.getHeight(null));
       this.setTitle("水果派");
       this.setLocationRelativeTo(null);
       this.setDefaultCloseOperation(3);
       this.setVisible(true);


       //键盘按键监听
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                basket.move(e);
            }
        });

    }

    /**
     * 窗体绘制方法
     * @param g the specified Graphics window
     */
    @Override
    public void paint(Graphics g){
          repaint();//更新画布
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if(num%120==0){
                Dessert dessert=new Dessert(tool.getDessert().get(ran.nextInt(11)));
                dessert.x=ran.nextInt(850);
                list.add(dessert);
            }

            //防止int数据溢出
          if(num==1000000){
              num=0;
          }
          num++;
         //利用双缓冲解决闪烁问题
          offScreenImage = this.createImage(basket.imageBg.getWidth(null),basket.imageBg.getHeight(null));//空的桌布
          Graphics gImage= offScreenImage.getGraphics();//利用缓冲区


        backGrund.paintSelf(gImage);
        basket.paintSelf(gImage);
        scoreBg.paintSelf(gImage);
        s1.paintSelf(gImage);
        s2.paintSelf(gImage);
        s3.paintSelf(gImage);
        s4.paintSelf(gImage);

        for (int i=0;i<list.size();i++) {
            list.get(i).paintSelf(gImage);
            list.get(i).move(basket);
             if( list.get(i).y>810 &&  list.get(i).x<= basket.x+ basket.widht){
                 if( list.get(i).x>=basket.x){ list.get(i).widht=0;}
                 if( list.get(i).x<=basket.x &&  list.get(i).x+ list.get(i).widht>= basket.x){ list.get(i).widht=0;}
             }
        }


       //调用绘制文本信息方法
        backGrund.paintStr(gImage);
        g.drawImage(offScreenImage,0,0,null);

    }


}
